<template>
  <div class="form-container">
    <star-canvas></star-canvas>
    <div class="register-form">
      <h2>注册</h2>

      <el-form :model="registerForm" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="registerForm.user_name" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="registerForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="重复密码">
          <el-input v-model="registerForm.passwordAgain" type="password" placeholder="请确认密码" />
        </el-form-item>
        <el-button type="primary" @click="submitRegisterForm">注册</el-button>
      </el-form>
    </div>
  </div>
</template>
  
<script>
import { ElMessage } from 'element-plus'
import { req_register } from '../../api'
import { response2ElMessage } from '../../utils/response-utils'
import StarCanvas from "../home-views/components/StarCanvas.vue";

export default {
  name: 'RegisterView',
  components: {StarCanvas},
  props: {

  },
  data() {
    return {
      registerForm: {
        user_name: '',
        email: '',
        password: '',
        passwordAgain: ''
      }
    }
  },
  methods: {
    async submitRegisterForm() {
      // 前端检验
      if (this.registerForm.user_name === '') {
        ElMessage.info("请输入用户名！")
        return
      }
      if (this.registerForm.email === '') {
        ElMessage.info("请输入邮箱！")
        return
      }
      if (this.registerForm.password === '') {
        ElMessage.info("请输入密码！")
        return
      }
      if (this.registerForm.passwordAgain === '') {
        ElMessage.info("请再次输入密码！")
        return
      }
      if (this.registerForm.passwordAgain !== this.registerForm.password) {
        ElMessage.info("两次密码输入不一致！")
        return
      }

      // 发送请求
      let response = await req_register(
        this.registerForm.user_name,
        this.registerForm.email,
        this.registerForm.password
      )

      // 回应
      response2ElMessage(response)

      // 跳转
      if (response.data['errno'] === 1) {
        this.$router.push({
          path: '/login'
        })
      }

    }
  },
  created() {

  },
  mounted() {

  }
}
</script>
<style scoped>
.form-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: calc(100vh - 140px); /* 减去顶部菜单的高度 */
}

.register-form {
  padding: 20px;
  border-radius: 10px;
  background: white;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  width: 300px;
}

.register-form h2 {
  text-align: center;
  margin-bottom: 20px;
}

.el-button {
  width: 100%;
  margin-top: 10px;
}

.el-input {
  margin-bottom: 10px;
}
</style>